package com.atguigu.daijia.order.MQ;

import com.atguigu.daijia.common.constant.RedisConstant;
import com.atguigu.daijia.model.entity.order.OrderInfo;
import com.atguigu.daijia.order.service.OrderInfoService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;

@Slf4j
@Component
public class listenOderDelayMessageListener {

    @Autowired
    private OrderInfoService orderInfoService;
    @Autowired
    private RedisTemplate redisTemplate;

    //监听订单延迟队列
    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(name = "delay.queue"),
            exchange = @Exchange(name = "delay.direct",delayed = "true"),
            key = "delay"
    ))
    public void listenOderDelayMessage(Long oderId){
        //查询订单
        OrderInfo orderInfo = orderInfoService.getById(oderId);
        //获取订单状态
        Integer status = orderInfo.getStatus();
        if (status==1){//判断是否处于等待接单状态
            orderInfo.setStatus(-1);//改为已经取消
            orderInfoService.updateById(orderInfo);
            //删除抢单标识
            String key = RedisConstant.ORDER_ACCEPT_MARK + oderId;
            redisTemplate.delete(key);
            log.info("订单超时自动取消，订单ID:{}",oderId);
        }

    }
}